import { Graph, Cell } from '@antv/x6';
import {
  AnswerTypeEnum,
  ChartNodeItem, CodeNodeItem,
  DataQueryNodeItem,
  EndNodeItem, IfElseItem, IterationNodeItem,
  llmNodeItem,
  nanoId,
  NodeConfig, NodeTypeEnum, ParamsExtractType, QaNodeItem, QuestionClassNodeItem, ReportNodeItem,
  RepositoryNodeItem,
  StartNodeInputVariablesItem, VariableAssignerItem, VariableTypeEnum
} from '@/view/graph/model/type';
import {NODES_MAP} from '@/view/graph/model/nodes';

export function GenerationNodeData(nodeItem: NodeConfig) {
  const { code, name, iteration_node_id } = nodeItem;
  const baseParams = {
    title: name,
    // 节点是否折叠
    isNodeFold: false,
    // 是否显示编辑icon
    isEdieIcon: false,
    // 输入是否折叠
    isInputFold: false,
    // 输出是否折叠
    isOutFold: false,
    // AI模型、知识库是否折叠
    isAiModelFold: false,
    // 提示词、搜索参数是否折叠
    isCallWordFold: false,
    //  提取参数
    isExtractParameter: false,
    // 代码是否折叠
    isCodeFold: false,
    // 节点是否点击
    isClick: false,
    // 时间戳
    lastModify: new Date(),
    nodeStatus: '',
    isPackUp: false,
    // form表单校验事件
    submitFormFunction: async () => {
      return new Promise<boolean>(resolve => {
        resolve(true);
      });
    }
  };
  // 知识库
  if (code === NODES_MAP.REPOSITORY) {
    const { input_variables, out_variables, retrieval_config, model_retrieval } =
      RepositoryNodeItem;
    return {
      ...baseParams,
      input_variables: input_variables.map(item => {
        return {
          ...item,
          uuId: nanoId()
        };
      }),
      out_variables: out_variables.map(item => {
        return {
          ...item,
          id: nanoId()
        };
      }),
      retrieval_config: retrieval_config.map(item => {
        return {
          ...item,
          uuId: nanoId()
        };
      }),
      model_retrieval
    };
  }
  // 模型
  if (code === NODES_MAP.MODEL) {
    const { input_variables, out_variables, model, prompt_template } = llmNodeItem;
    return {
      ...baseParams,
      input_variables: input_variables.map(item => {
        return {
          ...item,
          uuId: nanoId()
        };
      }),
      out_variables: out_variables.map(item => {
        return {
          ...item,
          id: nanoId()
        };
      }),
      model,
      prompt_template
    };
  }
  // 结束
  if (code === NODES_MAP.END) {
    const { type, out_variables, reply, stream } = EndNodeItem;
    return {
      ...baseParams,
      type: type,
      out_variables: out_variables.map(item => {
        return {
          ...item,
          uuId: nanoId()
        };
      }),
      stream,
      reply
    };
  }
  // 开始
  if (code === NODES_MAP.START) {
    return {
      input_variables: [
        {
          ...StartNodeInputVariablesItem,
          variable: 'query',
          label: 'query',
          description: '用户本轮对话输入内容',
          id: nanoId(),
          enums: StartNodeInputVariablesItem.enums.map(item => {
            return {
              ...item,
              key: nanoId()
            };
          })
        },
        // {
        //   ...StartNodeInputVariablesItem,
        //   variable: 'file',
        //   label: 'file',
        //   description: '上传附件，最多一个，不大于50M，支持xlsx、csv格式',
        //   required: false,
        //   type: VariableTypeEnum.FILE,
        //   id: nanoId(),
        //   enums: StartNodeInputVariablesItem.enums.map(item => {
        //     return {
        //       ...item,
        //       key: nanoId()
        //     };
        //   })
        // },
        // {
        //   ...StartNodeInputVariablesItem,
        //   variable: 'historylist',
        //   label: 'historylist',
        //   description: '上下文限制',
        //   required: false,
        //   type: VariableTypeEnum.OBJECT,
        //   value: '[]',
        //   id: nanoId(),
        //   enums: StartNodeInputVariablesItem.enums.map(item => {
        //     return {
        //       ...item,
        //       key: nanoId()
        //     };
        //   })
        // }
      ],
      ...baseParams
    };
  }
  // 意图识别
  if (code === NodeTypeEnum.QUESTION_CLASS) {
    const { input_variables, out_variables, model, prompt_template, category } =
      QuestionClassNodeItem;
    return {
      ...baseParams,
      input_variables: input_variables.map(item => {
        return {
          ...item,
          uuId: nanoId()
        };
      }),
      out_variables: out_variables.map(item => {
        return {
          ...item,
          id: nanoId()
        };
      }),
      model: model,
      prompt_template: prompt_template,
      category: category.map(item => {
        return {
          ...item,
          id: nanoId()
        };
      })
    };
  }
  // 数据查询
  if (code === NodeTypeEnum.DATA_QUERY) {
    const { input_variables, out_variables, config, chart_switch, drill_analysis } =
      DataQueryNodeItem;
    return {
      input_variables: input_variables.map(item => {
        return {
          ...item,
          uuId: nanoId()
        };
      }),
      out_variables: out_variables.map(item => {
        return {
          ...item,
          id: nanoId()
        };
      }),
      config: config.map(item => {
        return {
          ...item,
          id: nanoId()
        };
      }),
      chart_switch,
      drill_analysis,
      ...baseParams
    };
  }
  // 图表制作
  if (code === NodeTypeEnum.CHAT) {
    const { input_variables, out_variables, config } = ChartNodeItem;
    return {
      input_variables: input_variables.map(item => {
        return {
          ...item,
          uuId: nanoId()
        };
      }),
      out_variables: out_variables.map(item => {
        return {
          ...item,
          id: nanoId()
        };
      }),
      config: config.map(item => {
        return {
          ...item,
          id: nanoId()
        };
      }),
      ...baseParams
    };
  }
  //  分支
  if (code === NodeTypeEnum.CONDITIONAL_BRANCH) {
    const { comparison_operator, values } = IfElseItem;
    return {
      case: [
        {
          case_id: nanoId(),
          comparison_operator,
          values: values.map(item => {
            return {
              ...item,
              id: nanoId()
            };
          })
        },
        {
          case_id: nanoId(),
          comparison_operator: '',
          values: []
        }
      ],
      ...baseParams
    };
  }
  // 代码提取
  if (code === NodeTypeEnum.PARAMETER_EXTRACTION) {
    const { input_variables, out_variables, model, params_extract, prompt_template } =
      VariableAssignerItem;
    return {
      model,
      prompt_template,
      input_variables: input_variables.map(item => {
        return {
          ...item,
          uuId: nanoId()
        };
      }),
      out_variables: out_variables,
      params_extract: params_extract.map(item => {
        return {
          ...item,
          id: nanoId(),
          type: ParamsExtractType[0]
        };
      }),
      ...baseParams
    };
  }
  // 代码
  if (code === NodeTypeEnum.CODE) {
    const { input_variables, out_variables, code, code_language } = CodeNodeItem;
    return {
      input_variables: input_variables.map(item => {
        return {
          ...item,
          uuId: nanoId()
        };
      }),
      out_variables: out_variables.map(item => {
        return {
          ...item,
          id: nanoId()
        };
      }),
      code,
      code_language,
      ...baseParams
    };
  }
  // 报告
  if (code === NodeTypeEnum.REPORT) {
    const { input_variables, out_variables, config } = ReportNodeItem;
    return {
      input_variables: input_variables.map(item => {
        return {
          ...item,
          uuId: nanoId()
        };
      }),
      out_variables: out_variables.map(item => {
        return {
          ...item,
          id: nanoId()
        };
      }),
      config: {
        ...config
      },
      ...baseParams
    };
  }
  // 问答
  if (code === NodeTypeEnum.QA) {
    const { input_variables, question, answer_type, out_variables, options_answer } = QaNodeItem;
    return {
      input_variables: input_variables.map(item => {
        return {
          ...item,
          uuId: nanoId()
        };
      }),
      out_variables: out_variables.map(item => {
        return {
          ...item,
          id: nanoId()
        };
      }),
      options_answer: options_answer.map(item => {
        return {
          ...item,
          option_id: nanoId()
        };
      }),
      question,
      answer_type,
      ...baseParams
    };
  }
  // 批处理
  if (code === NodeTypeEnum.ITERATION) {
    const { input_variables, out_variables, parallel_nums, max_process_data } = IterationNodeItem;
    return {
      input_variables: input_variables.map(item => {
        return {
          ...item,
          valueLabel: '变量取值',
          uuId: nanoId()
        };
      }),
      out_variables: out_variables.map(item => {
        return {
          ...item,
          valueLabel: '变量取值',
          variableType: '',
          isValue: true,
          id: nanoId()
        };
      }),
      parallel_nums,
      max_process_data,
      ...baseParams
    };
  }

  // 批处理体
  if (code === NodeTypeEnum.ITERATION_BODY) {
    return {
      ...baseParams,
      iteration_node_id
    };
  }
  // 自定义工具和workflow工具
  if ([NodeTypeEnum.CUSTOM_TOOL, NodeTypeEnum.WORKFLOW_TOOL].includes(code)) {
    return {
      ...baseParams,
      tool_id: nodeItem.tool_id,
      input_variables: nodeItem.input_variables,
      out_variables: nodeItem.out_variables
    };
  }
  return baseParams;
}

export function ValidateEdgeRules(graph: any, edge: any) {
  const sourceNode = graph.getCellById(edge.source.cell);
  // if (sourceNode?.shape === NODES_MAP.START) {
  //
  // }
}

export function ValidateMagnetRules(graph: Graph, cell: Cell) {
  const nodeList = graph?.getNodes() || [];
  const edgeList = graph?.getEdges() || [];
  const sourceEdgeList = edgeList?.filter((item: any) => item.source.cell === cell.id);

  // if (cell.shape === NODES_MAP.START && sourceEdgeList.length >= 1) {
  //   return {
  //     result: false,
  //     msg: '开始最多配置1条输出线。'
  //   };
  // }
  return {
    result: true,
    msg: ''
  };
}

/**
 * 保存校验
 */
export const checkGraphData = (graph: Graph): string => {
  const nodeList = graph.getNodes();
  const edgeList = graph?.getEdges();
  for (let i = 0; i < nodeList.length; i++) {
    const { shape } = nodeList[i];
    const outgoingEdges = graph.getOutgoingEdges(nodeList[i]);
    if (shape === NodeTypeEnum.QUESTION_CLASS) {
      const { title } = nodeList[i].getData();
      const ports = nodeList[i].getPorts();
      for (let j = 0; j < ports.length; j++) {
        const previousItem = ports[j];
        if (previousItem.group === 'right') {
          if (!edgeList.some(item => item.getData()?.categoryId === previousItem.id)) {
            return title + '节点异常，输出节点缺失';
          }
        }
      }
    }
    if (shape === NodeTypeEnum.CONDITIONAL_BRANCH) {
      const { title } = nodeList[i].getData();
      const ports = nodeList[i].getPorts();
      for (let j = 0; j < ports.length; j++) {
        const previousItem = ports[j];
        if (previousItem.group === 'right') {
          if (!edgeList.some(item => item.getData()?.case_id === previousItem.id)) {
            return title + '节点异常，输出节点缺失';
          }
        }
      }
    }

    if (shape === NodeTypeEnum.QA) {
      const { title, answer_type } = nodeList[i].getData();
      if (answer_type === AnswerTypeEnum.OPTIONAL_ANSWER) {
        const ports = nodeList[i].getPorts();
        for (let j = 0; j < ports.length; j++) {
          const previousItem = ports[j];
          if (previousItem.group === 'right') {
            if (!edgeList.some(item => item.getData()?.option_id === previousItem.id)) {
              return title + '节点异常，输出节点缺失';
            }
          }
        }
      }
    }
  }
  return '';
};
